package com.nx.platform.es.biz.esspider.handler;


import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreMaps;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 根据分割特定字符分割字段
 * <p>
 * Created by  on 2017/4/7.
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleArrayHandler extends AbstractSimpleHandler {
    private static final Type PARAMS_TYPE = new TypeToken<List<Long>>() {}.getType();
    private static final Gson GSON = new GsonBuilder().create();
    private String field;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        field = MoreMaps.getString(settings, "field");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(field), "field null or empty");
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.values().forEach((Item item) -> {
            Map<String, Object> doc = item.getDoc();
            Object oriValue = doc.get(field);
            if (oriValue instanceof String) {
                List<String> temp = GSON.fromJson(String.valueOf(oriValue), PARAMS_TYPE);
                if (temp == null) {
                    temp = new ArrayList<>();
                }
                doc.replace(field, temp);
            }
        });
    }

}
